from typing import Dict
from fastapi import UploadFile, HTTPException


class FileParser:
    """文件内容解析工具类（不保存文件）"""

    SUPPORTED_TYPES = {
        'application/pdf': 'pdf',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
        'application/msword': 'doc'
    }

    @classmethod
    def parse_file(cls, file: UploadFile) -> Dict[str, str]:
        """解析上传文件内容"""
        try:
            # 1. 验证文件类型
            file_type = file.content_type

            if file_type not in cls.SUPPORTED_TYPES:
                raise ValueError(f"Unsupported file type: {file_type}")

            # 2. 读取文件内容
            file_content = file.file.read()

            # 3. 根据类型解析内容
            if file_type == 'application/pdf':
                text = cls._parse_pdf(file_content)
            else:  # Word 文档（doc 或 docx）
                text = cls._parse_word(file_content)

            return {
                "success": True,
                "content": text,
                "file_type": cls.SUPPORTED_TYPES[file_type],
                "original_name": file.filename
            }

        except Exception as e:
            raise HTTPException(
                status_code=400,
                detail=f"文件解析失败: {str(e)}"
            )
        finally:
            file.file.seek(0)  # 重置文件指针

    @staticmethod
    def _parse_pdf(file_content: bytes) -> str:
        """解析 PDF 内容"""
        from PyPDF2 import PdfReader
        import io

        pdf_file = io.BytesIO(file_content)
        reader = PdfReader(pdf_file)
        return "\n".join([page.extract_text() or "" for page in reader.pages])

    @staticmethod
    def _parse_word(file_content: bytes) -> str:
        """解析 Word 内容（docx）"""
        from docx import Document
        import io

        doc_file = io.BytesIO(file_content)
        doc = Document(doc_file)
        return "\n".join([para.text for para in doc.paragraphs])
